// 完整数据种子脚本 - 生成前端需要的所有初始数据
const mongoose = require('mongoose');
const { connectDB, disconnectDB } = require('../config/db');
require('dotenv').config();

// 导入模型
const User = require('../models/user');
const Student = require('../models/student');
const Teacher = require('../models/teacher');
const Class = require('../models/class');
const Dormitory = require('../models/dormitory');
const Grade = require('../models/grade');
const Attendance = require('../models/attendance');

// 学院列表
const academies = ['人工智能', '数智传媒', '鸿蒙生态开发', '云计算', '元宇宙'];

// 班级基础数据
const baseClasses = [
  { name: '2509A', stage: '专业阶段', tier: '专业一' },
  { name: '2508A', stage: '专业阶段', tier: '专业二' },
  { name: '2508B', stage: '专业阶段', tier: '专业二' },
  { name: '2507A', stage: '专业阶段', tier: '专业三' },
  { name: '2507B', stage: '专业阶段', tier: '专业三' },
  { name: '2506A', stage: '专业阶段', tier: '专业四' },
  { name: '2505A', stage: '专业阶段', tier: '专业五' },
  { name: '2504A', stage: '专高阶段', tier: '专高一' },
  { name: '2503A', stage: '专高阶段', tier: '专高二' },
  { name: '2502A', stage: '专高阶段', tier: '专高三' },
  { name: '2502C', stage: '专高阶段', tier: '专高三' },
  { name: '2501A', stage: '专高阶段', tier: '专高四' },
  { name: '2412A', stage: '专高阶段', tier: '专高五' },
  { name: '2412C', stage: '专高阶段', tier: '专高五' },
  { name: '2411A', stage: '专高阶段', tier: '专高六' },
  { name: '2411B', stage: '专高阶段', tier: '专高六' },
  { name: '2411C', stage: '专高阶段', tier: '专高六' },
  { name: '2410A', stage: '实训阶段', tier: '实训一' },
  { name: '2410B', stage: '实训阶段', tier: '实训一' },
  { name: '2410C', stage: '实训阶段', tier: '实训一' },
  { name: '2410D', stage: '实训阶段', tier: '实训一' },
  { name: '2409A', stage: '实训阶段', tier: '实训二' },
  { name: '2409B', stage: '实训阶段', tier: '实训二' },
  { name: '2409C', stage: '实训阶段', tier: '实训二' },
  { name: '2408A', stage: '实训阶段', tier: '实训三' },
  { name: '2408B', stage: '实训阶段', tier: '实训三' }
];

// 生成随机中文名字
const surnames = ['王', '李', '张', '刘', '陈', '杨', '赵', '黄', '周', '吴', '徐', '孙', '胡', '朱', '高', '林', '何', '郭', '马', '罗'];
const givenNames = ['伟', '芳', '娜', '秀英', '敏', '静', '丽', '强', '磊', '军', '洋', '勇', '艳', '杰', '娟', '涛', '明', '超', '秀兰', '霞'];

function generateName() {
  const surname = surnames[Math.floor(Math.random() * surnames.length)];
  const given1 = givenNames[Math.floor(Math.random() * givenNames.length)];
  const given2 = Math.random() > 0.5 ? givenNames[Math.floor(Math.random() * givenNames.length)] : '';
  return surname + given1 + given2;
}

// 生成随机手机号
function generatePhone() {
  return '13' + Math.floor(Math.random() * 900000000 + 100000000);
}

// 生成随机日期
function generateDate(startYear, endYear) {
  const start = new Date(startYear, 0, 1);
  const end = new Date(endYear, 11, 31);
  return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
}

async function seedData() {
  try {
    console.log('🚀 开始连接数据库...');
    await connectDB();
    console.log('✅ 数据库连接成功\n');
    
    // 清除现有数据
    console.log('🧹 清理现有数据...');
    await User.deleteMany({});
    await Student.deleteMany({});
    await Teacher.deleteMany({});
    await Class.deleteMany({});
    await Dormitory.deleteMany({});
    await Grade.deleteMany({});
    await Attendance.deleteMany({});
    console.log('✅ 现有数据清理完成\n');
    
    // 1. 创建管理员用户
    console.log('👤 创建管理员用户...');
    const adminUser = await User.create({
      username: 'admin',
      email: 'admin@example.com',
      password: '123456', // 实际应该加密
      role: 'admin',
      name: '系统管理员',
      phone: '13800138000'
    });
    console.log(`✅ 创建管理员: ${adminUser.username}\n`);
    
    // 2. 创建教师（导员和讲师）
    console.log('👨‍🏫 创建教师数据...');
    const teachers = [];
    const teacherNames = ['张导员', '王导员', '李导员', '赵导员', '刘导员', '陈导员', '杨导员', '黄导员'];
    const lecturerNames = ['张讲师', '王讲师', '李讲师', '赵讲师', '刘讲师', '陈讲师', '杨讲师', '黄讲师'];
    
    // 创建导员
    for (let i = 0; i < 8; i++) {
      const teacher = await Teacher.create({
        name: teacherNames[i],
        email: `teacher${i+1}@example.com`,
        phone: generatePhone(),
        role: 'instructor',
        status: 'active',
        subject: '班级管理',
        department: '教务处'
      });
      teachers.push(teacher);
    }
    
    // 创建讲师
    for (let i = 0; i < 8; i++) {
      const lecturer = await Teacher.create({
        name: lecturerNames[i],
        email: `lecturer${i+1}@example.com`,
        phone: generatePhone(),
        role: 'lecturer',
        status: 'active',
        subject: '专业课程',
        department: '教学部'
      });
      teachers.push(lecturer);
    }
    console.log(`✅ 创建了 ${teachers.length} 位教师\n`);
    
    // 3. 创建班级
    console.log('📚 创建班级数据...');
    const classes = [];
    let classCounter = 0;
    
    for (const academy of academies) {
      for (const baseClass of baseClasses) {
        const advisorIndex = classCounter % 8;
        const lecturerIndex = classCounter % 8;
        
        const newClass = await Class.create({
          name: baseClass.name,
          stage: baseClass.stage,
          academy: academy,
          advisorId: teachers[advisorIndex]._id,
          advisorName: teachers[advisorIndex].name,
          lecturerId: teachers[8 + lecturerIndex]._id,
          lecturerName: teachers[8 + lecturerIndex].name,
          studentCount: 0,
          subjects: ['chinese', 'math', 'english'],
          status: 'active'
        });
        
        classes.push(newClass);
        classCounter++;
      }
    }
    console.log(`✅ 创建了 ${classes.length} 个班级\n`);
    
    // 4. 创建宿舍
    console.log('🏠 创建宿舍数据...');
    const dormitories = [];
    
    // 学四舍（女生宿舍）- 6层，每层10间
    for (let floor = 1; floor <= 6; floor++) {
      for (let room = 1; room <= 10; room++) {
        const dormitory = await Dormitory.create({
          building: '学四舍',
          roomNumber: `${floor}${room.toString().padStart(2, '0')}`,
          type: 'female',
          capacity: 8,
          currentOccupancy: 0,
          students: [],
          floor: floor,
          status: 'active',
          notes: `学四舍 ${floor}层 女生宿舍`
        });
        dormitories.push(dormitory);
      }
    }
    
    // 学三舍（男生宿舍）- 6层，每层10间
    for (let floor = 1; floor <= 6; floor++) {
      for (let room = 1; room <= 10; room++) {
        const dormitory = await Dormitory.create({
          building: '学三舍',
          roomNumber: `${floor}${room.toString().padStart(2, '0')}`,
          type: 'male',
          capacity: 8,
          currentOccupancy: 0,
          students: [],
          floor: floor,
          status: 'active',
          notes: `学三舍 ${floor}层 男生宿舍`
        });
        dormitories.push(dormitory);
      }
    }
    
    // 皇悦三期（男生宿舍）- 6层，每层5间
    for (let floor = 1; floor <= 6; floor++) {
      for (let room = 1; room <= 5; room++) {
        const dormitory = await Dormitory.create({
          building: '皇悦三期',
          roomNumber: `93${floor}${room.toString().padStart(2, '0')}`,
          type: 'male',
          capacity: 8,
          currentOccupancy: 0,
          students: [],
          floor: floor,
          status: 'active',
          notes: `皇悦三期 ${floor}层 男生宿舍`
        });
        dormitories.push(dormitory);
      }
    }
    
    // 皇悦一期（男生宿舍）- 6层，每层10间
    for (let floor = 1; floor <= 6; floor++) {
      for (let room = 1; room <= 10; room++) {
        const dormitory = await Dormitory.create({
          building: '皇悦一期',
          roomNumber: `91${floor}${room.toString().padStart(2, '0')}`,
          type: 'male',
          capacity: 8,
          currentOccupancy: 0,
          students: [],
          floor: floor,
          status: 'active',
          notes: `皇悦一期 ${floor}层 男生宿舍`
        });
        dormitories.push(dormitory);
      }
    }
    
    console.log(`✅ 创建了 ${dormitories.length} 间宿舍\n`);
    
    // 5. 创建学生
    console.log('🎓 创建学生数据...');
    const students = [];
    let studentCounter = 1;
    
    // 为每个班级创建3-5名学生
    for (const cls of classes) {
      const studentCount = Math.floor(Math.random() * 3) + 3; // 3-5名学生
      
      for (let i = 0; i < studentCount; i++) {
        const gender = Math.random() > 0.5 ? 'male' : 'female';
        
        // 根据性别分配宿舍
        let selectedDormitory;
        if (gender === 'female') {
          // 女生宿舍（学四舍）
          const femaleDorms = dormitories.filter(d => d.type === 'female' && d.currentOccupancy < d.capacity);
          selectedDormitory = femaleDorms[Math.floor(Math.random() * femaleDorms.length)];
        } else {
          // 男生宿舍（学三舍、皇悦三期、皇悦一期）
          const maleDorms = dormitories.filter(d => d.type === 'male' && d.currentOccupancy < d.capacity);
          selectedDormitory = maleDorms[Math.floor(Math.random() * maleDorms.length)];
        }
        
        const student = await Student.create({
          name: generateName(),
          studentId: `S2023${studentCounter.toString().padStart(4, '0')}`,
          gender: gender,
          stage: cls.stage === '专业阶段' ? 'freshman' : (cls.stage === '专高阶段' ? 'sophomore' : 'junior'),
          academy: cls.academy,
          classId: cls._id,
          dormitoryId: selectedDormitory ? selectedDormitory._id : undefined,
          dateOfBirth: generateDate(2003, 2006).toISOString().split('T')[0],
          admissionDate: generateDate(2020, 2023).toISOString().split('T')[0],
          phone: generatePhone(),
          email: `student${studentCounter}@example.com`,
          address: `某某省某某市某某区某某路${Math.floor(Math.random() * 100)}号`,
          status: 'active'
        });
        
        students.push(student);
        studentCounter++;
        
        // 更新宿舍入住人数
        if (selectedDormitory) {
          await Dormitory.findByIdAndUpdate(selectedDormitory._id, {
            $inc: { currentOccupancy: 1 },
            $push: { students: student._id }
          });
        }
        
        // 更新班级学生数量
        await Class.findByIdAndUpdate(cls._id, {
          $inc: { studentCount: 1 }
        });
      }
    }
    
    console.log(`✅ 创建了 ${students.length} 名学生\n`);
    
    // 6. 创建成绩数据
    console.log('📊 创建成绩数据...');
    const grades = [];
    const subjects = ['chinese', 'math', 'english'];
    const examTypes = ['周考', '月考', '期中考试', '期末考试'];
    
    // 为每个学生创建一些成绩记录
    for (const student of students.slice(0, 50)) { // 只为前50名学生创建成绩
      for (const subject of subjects) {
        const grade = await Grade.create({
          term: '2025.9.22-2025.10.24',
          examType: examTypes[Math.floor(Math.random() * examTypes.length)],
          studentId: student._id,
          studentName: student.name,
          subject: subject,
          score: Math.floor(Math.random() * 40) + 60, // 60-100分
          academy: student.academy,
          className: (await Class.findById(student.classId)).name
        });
        grades.push(grade);
      }
    }
    
    console.log(`✅ 创建了 ${grades.length} 条成绩记录\n`);
    
    // 7. 创建考勤数据
    console.log('✅ 创建考勤数据...');
    const attendances = [];
    const attendanceStatuses = ['present', 'absent', 'late'];
    const today = new Date();
    
    // 为前30名学生创建最近7天的考勤
    for (let day = 0; day < 7; day++) {
      const date = new Date(today);
      date.setDate(date.getDate() - day);
      
      for (const student of students.slice(0, 30)) {
        const attendance = await Attendance.create({
          date: date.toISOString().split('T')[0],
          studentId: student._id,
          classId: student.classId,
          status: attendanceStatuses[Math.floor(Math.random() * attendanceStatuses.length)],
          remark: ''
        });
        attendances.push(attendance);
      }
    }
    
    console.log(`✅ 创建了 ${attendances.length} 条考勤记录\n`);
    
    // 汇总信息
    console.log('\n' + '='.repeat(50));
    console.log('📊 数据生成完成！');
    console.log('='.repeat(50));
    console.log(`👤 管理员用户: 1 个`);
    console.log(`👨‍🏫 教师: ${teachers.length} 位`);
    console.log(`📚 班级: ${classes.length} 个`);
    console.log(`🏠 宿舍: ${dormitories.length} 间`);
    console.log(`🎓 学生: ${students.length} 名`);
    console.log(`📊 成绩记录: ${grades.length} 条`);
    console.log(`✅ 考勤记录: ${attendances.length} 条`);
    console.log('='.repeat(50));
    console.log('\n✨ 所有数据已成功导入 MongoDB！');
    console.log('\n📝 登录信息:');
    console.log('   用户名: admin');
    console.log('   密码: 123456');
    console.log('   邮箱: admin@example.com\n');
    
  } catch (error) {
    console.error('❌ 数据生成失败:', error);
    throw error;
  } finally {
    await disconnectDB();
    console.log('👋 数据库连接已关闭');
    process.exit(0);
  }
}

// 运行种子脚本
seedData();

